package com.atguigu.msmservice.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SendMailService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final static Logger LOGGER = LoggerFactory.getLogger(SendMailService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sendFrom;

    /**
     * 发送简单邮件
     *
     * @param sendTo  接收人
     */
    public void sendSimpleMail(String sendTo) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sendFrom);
        message.setTo(sendTo);
        message.setSubject("谷粒学苑登录验证码");
        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
        message.setText(code);
        mailSender.send(message);
        //存储到redis，有效期五分钟
        redisTemplate.opsForValue().set(sendTo,code,5, TimeUnit.MINUTES);
    }


    /**
     * 发送HTML格式的邮件，并可以添加附件
     *
     * @param sendTo  接收人
     * @param subject 邮件主题
     * @param content 邮件内容（html）
     * @param files   附件
     * @throws MessagingException
     */
    public void sendHtmlMail(String sendTo, String subject, String content, List<File> files) {
        MimeMessage message = mailSender.createMimeMessage();
        // true表示需要创建一个multipart message
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sendFrom);
            helper.setTo(sendTo);
            helper.setSubject(subject);
            helper.setText(content, true);

            //添加附件
            for (File file : files) {
                helper.addAttachment(file.getName(), new FileSystemResource(file));
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            LOGGER.warn("邮件发送出错：{}", e);
        }
    }


}
